package com.viknix.threadpool.manager.server.controller.cluster;

import com.viknix.threadpool.manager.cluster.core.Member;
import com.viknix.threadpool.manager.cluster.core.ServerMemberManager;
import com.viknix.threadpool.manager.cluster.enums.NodeState;
import com.viknix.threadpool.manager.server.dependence.constant.Commons;
import com.viknix.threadpool.manager.server.dependence.result.RestResult;
import com.viknix.threadpool.manager.server.dependence.result.RestResultUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Dongqi
 * @Date: 2021/11/17 20:08
 * @Version 1.0
 * @Description: 集群通信接口。
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(Commons.TPM_CORE_CONTEXT + "/cluster")
public class TpmClusterController {

    private final ServerMemberManager memberManager;

    /**
     * 其他节点返回自己的元数据信息。
     * Other nodes return their own metadata information.
     *
     * @param node {@link Member}
     * @return {@link RestResult}
     */
    @PostMapping(value = {"/report"})
    public RestResult<String> report(@RequestBody Member node) {
        if (!node.check()) {
            return RestResultUtils.failedWithMsg(400, "Node information is illegal");
        }
        node.setState(NodeState.UP);
        node.setFailAccessCnt(0);

        boolean result = memberManager.update(node);

        return RestResultUtils.success(Boolean.toString(result));
    }
}
